<template>
  <div>
    <mk-breadcrumb  :breadcrumb-data="breadcrumbData"></mk-breadcrumb>
      <el-scrollbar :wrapStyle="[{maxHeight:(bodyHeight-fixedHeightSmall)+'px'}]">
    <div class="content-box">
      <div class="add-article-box">
        <!-- 写文章 -->
        <div class="add-article-content-box">
          <el-form :model="articleDetailData" ref="articleForm" label-position="right" label-width="96px"
                   class="top-form" :rules="submitFormRules">
            <el-form-item label="标题" prop="title">
              <el-input v-model="articleDetailData.title" placeholder="请输入标题（必填）" :minlength='5' :maxlength='30'></el-input>
            </el-form-item>
            <el-form-item label="来源" prop='source'>
              <el-input v-model="articleDetailData.source" placeholder="请输入来源（必填）" :maxlength='8'></el-input>
            </el-form-item>
            <el-form-item label="分类" prop="categoryId">
              <el-select v-model.number="articleDetailData.categoryId" placeholder="请选择分类（必选）" :disabled="onlyPub">
                <el-option v-for='item in articleItem.categories' :label="item.name" :value="item.id"
                           :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="食谱分类" prop='dietTypeId' v-if="articleDetailData.categoryId===243">
              <el-select v-model="articleDetailData.dietTypeId" placeholder="请选择食谱类别（必选）" :disabled="onlyPub">
                <el-option v-for='item in dietTypeArr' :label="item.name" :value="item.id"
                           :key="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="简介" prop='summary'>
              <el-input v-model="articleDetailData.summary" placeholder="请输入简介" type="textarea" :rows="6"
                        resize="none"></el-input>
            </el-form-item>
            <el-form-item label='文章内容' prop='content' class="ckeditor-content-size">
              <mk-ckeditor v-model="articleDetailData.content" class="article-editor"></mk-ckeditor>
              <p style="color:#83a0a5;font-size:14px;text-align: left;">建议文章内容中的图片宽度不超过800</p>
            </el-form-item>
            <el-form-item label="封面" prop="imageId">
              <el-upload
                class="avatar-uploader"
                accept=".jpeg, .jpg, .png, .gif"
                :action="'/upload/image.json'"
                :show-file-list="false"
                :data="{'width':400,'height':400}"
                :on-success="handleSuccess"
                :before-upload="beforeCoverUpload"
                name="image">
                <img v-if="imageUrl" :src="imageUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
              <span style="color:#83a0a5;font-size:14px;">建议上传尺寸400*400</span>
            </el-form-item>

            <template v-if="!onlyPub">

              <div v-if="articleDetailData.siteSelect.length === 0" style="margin-bottom:20px;">
                <div style="color: #81939e;display: inline-block;width:76px;font-size:14px;text-align: right;padding-right:20px;">所属站点</div>
                <div class='addNode' @click='addApproval' style="font-size:14px;">
                  <i class='el-icon-plus' ></i> 添加站点
                </div>
              </div>

              <template v-else>
                <template v-for='(item,index) in articleDetailData.siteSelect'>
                  <el-form-item :label='index===0?"所属站点":""' style=''>
                    <el-col :span="22">
                      <el-form-item style='width:100%;' :prop="'siteSelect.'+index+'.siteIdArr'" :rules="{ required: true, type:'array',message: '请选择站点'}" :key='"siteIdArr_"+item.key'>
                        <el-cascader
                          :props="options"
                          :options="siteArr"
                          multiple
                          v-model="item.siteIdArr"
                          placeholder="请选择站点（必选）">
                        </el-cascader>
                      </el-form-item>
                    </el-col>
                    <el-col :span='2' class='textAlignCenter'>
                      <i class='el-icon-error cursorPointer' style='color:#fb5f5f;font-size:16px;' @click='deleteApprovalInput(item)'></i>
                    </el-col>
                  </el-form-item>
                </template>

                <div  style="margin-bottom:20px;">
                  <div style="color: #81939e;visibility:hidden;display: inline-block;width:76px;font-size:14px;text-align: right;padding-right:20px;">所属站点</div>
                  <div class='addNode' @click='addApproval' style="font-size:14px;">
                    <i class='el-icon-plus' ></i> 添加站点
                  </div>
                </div>

              </template>

            </template>
            <template v-else>
              <el-form-item label="所属站点">
                {{siteName}}
              </el-form-item>
            </template>


            <el-form-item label="展示位置" prop="positionCheckList">
              <el-checkbox-group v-model="articleDetailData.positionCheckList">
                <el-checkbox v-for="position in positionOptions" :label="position" :key="position"></el-checkbox>
              </el-checkbox-group>
            </el-form-item>

              <div style = 'position:relative;' v-if="!onlyPub">
                <el-form-item label="发送时间" prop="publishType" v-if="!onlyPub">
                  <el-radio-group v-model="articleDetailData.publishType">
                    <el-radio label="Now">立即发送</el-radio>
                    <el-radio label="Timing">定时发送</el-radio>
                  </el-radio-group>
                </el-form-item>

                <template v-if="articleDetailData.publishType === 'Timing'" >
                  <el-form-item label="" prop="timingPublishTime_" style="width:300px;position:absolute;top:0px;left:220px;">
                    <el-date-picker :picker-options="datePicker" v-model="articleDetailData.timingPublishTime_" type="datetime" format="yyyy-MM-dd HH:mm" placeholder="请选择指定时间（必选）">
                    </el-date-picker>
                  </el-form-item>
                </template>
              </div>

          </el-form>
        </div>

        <div class="ensure-save-box" v-if="!onlyPub || (dataSource && dataSource == 'OPERATION')">
            <el-button class="btnStyle color1" type="primary"  v-loading.fullscreen.lock="fullscreenLoading"
                       @click="pubArticle('articleForm')"  v-if="!onlyPub || (dataSource && dataSource == 'OPERATION')　">发布
            </el-button>

            <el-button class="btnStyle color2" type="primary"  v-loading.fullscreen.lock="fullscreenLoading"
                       @click="saveArticle('articleForm')" v-if="!onlyPub">保存
            </el-button>
        </div>

      </div>
    </div>
      </el-scrollbar>
  </div>
</template>

<script>
  import MkBreadcrumb from '../../../components/MkBreadcrumb.vue'
  import {mapState} from 'vuex'
  import articleService from '../../../services/article'
  export default {
    name: 'addArticle',
    components: {
      MkBreadcrumb,
    },
    methods: {
      beforeCoverUpload(file) {
        let fileName = file.name;
        let suffix = fileName.substr(file.name.lastIndexOf("."), fileName.length).toLowerCase();
        let support = false;
        for (let i = 0; i < this.supportFile.length; i++) {
          if (suffix === this.supportFile[i]) {
            support = true;
            break;
          }
        }
        if (!support) {
          this.$message.warning('只能上传图片格式的文件');
          return support;
        }
        const isLt5M = file.size / 1024 / 1024 < 5;
        if (!isLt5M) {
          this.$message.error('图片大小不能超过 5MB!');
        }
        return isLt5M;
      },
      handleSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw);
        this.articleDetailData.imageId = res.data.fileId;
      },
      handlePosition() {
        let positionsArr = [];
        let labels = this.articleDetailData.positionCheckList;
        for (let i = 0; i < labels.length; i++) {
          switch (labels[i]) {
            case '热点资讯' :
              positionsArr.push('COMMUNITY_HEADLINES')
              break;
            case '社区公告' :
              positionsArr.push('COMMUNITY_ANNOUNCEMENT')
              break;
//            case '活动入口':
//              positionsArr.push('ARTICLE_FOR_ACTIVE');
//              break;
            case '健康食谱':
              positionsArr.push('HEALTH_DIET')
                  break;
          }
        }
        this.articleDetailData.positions = positionsArr.join(',');
      },
      pubArticle(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {};
            let articleDetailData = this.articleDetailData;

            this.handlePosition();

            if (!this.isSubmit) {
              if (!articleDetailData.id) {
                let siteIdsArr = [];
                articleDetailData.needPublish = true;
                if(articleDetailData.siteSelect.length === 0){
                  this.$message.warning('请选择所属站点');
                  return;
                }
                for(let i=0; i<articleDetailData.siteSelect.length;i++) {
                  let item = articleDetailData.siteSelect[i];
                  let siteId = item.siteIdArr[item.siteIdArr.length - 1];
                  if(siteIdsArr.indexOf(siteId) === -1) {
                    siteIdsArr.push(siteId);
                  }
                }
                if(articleDetailData.siteSelect.length !== siteIdsArr.length) {
                  this.$message.warning('选择的站点有重复');
                  return;
                }
                articleDetailData.siteIds = siteIdsArr.join(',');
                if(articleDetailData.publishType === 'Timing'){
                  articleDetailData.timingPublishTime = new Date(articleDetailData.timingPublishTime_).pattern('yyyy-MM-dd HH:mm:ss');
                  if(new Date(this.articleDetailData.timingPublishTime_).getTime() < new Date().getTime()) {
                    this.$message.warning('发布时间必须晚于当前时间');
                    return;
                  }
                }else{
                  articleDetailData.timingPublishTime = '';
                }
                for(let i in articleDetailData) {
                  if(i!=='siteSelect' && i!== 'timingPublishTime_'&& i!=='positionCheckList'&& i!=='id') {
                    param[i] = articleDetailData[i];
                  }
                }

                if(param.categoryId !== 243) {
                  param.dietTypeId = '';
                }
                this.isSubmit = true;
                this.fullscreenLoading = true;
                articleService.addArticleServer(param,  (data) =>{
                  this.$message({
                    message:'发布成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/articleMgt'});
                  },1000)
                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              } else {
                  param = {
                    id: articleDetailData.id,
                    content: articleDetailData.content,
                    imageId: articleDetailData.imageId,
                    positions: articleDetailData.positions,
                    source: articleDetailData.source,
                    summary: articleDetailData.summary,
                    title: articleDetailData.title,
                  }
                this.isSubmit = true;
                this.fullscreenLoading = true;
                articleService.editArticleServer(param,  (data)=> {
                  this.$message({
                    message:'发布成功',
                    type:'success',
                    duration:1000
                  });
                  setTimeout(()=>{
                    this.$router.push({path: '/operationMgt/articleMgt'});
                  },1000)

                },(data)=>{
                  this.isSubmit = false;
                  this.fullscreenLoading = false;
                })
              }
            }

          }
        })
      },
      saveArticle(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            let param = {};
            let siteIdsArr = [];
            this.articleDetailData.needPublish = false;
            if(this.articleDetailData.siteSelect.length === 0){
                this.$message.warning('请选择所属站点');
                return;
            }
            for(let i=0; i<this.articleDetailData.siteSelect.length;i++) {
              let item = this.articleDetailData.siteSelect[i];
              let siteId = item.siteIdArr[item.siteIdArr.length - 1];
              if(siteIdsArr.indexOf(siteId) === -1) {
                siteIdsArr.push(siteId);
              }
            }
            if(this.articleDetailData.siteSelect.length !== siteIdsArr.length) {
              this.$message.warning('选择的站点有重复');
              return;
            }
            this.articleDetailData.siteIds = siteIdsArr.join(',');
            if(this.articleDetailData.publishType === 'Timing'){
              this.articleDetailData.timingPublishTime = new Date(this.articleDetailData.timingPublishTime_).pattern('yyyy-MM-dd HH:mm:ss');
              if(new Date(this.articleDetailData.timingPublishTime_).getTime() < new Date().getTime()) {
                this.$message.warning('发布时间必须晚于当前时间');
                return;
              }
            }else{
              this.articleDetailData.timingPublishTime = '';
            }

           this.handlePosition();

            for(let i in this.articleDetailData) {
                if(i!=='siteSelect' && i!== 'timingPublishTime_' && i!=='positionCheckList') {
                    param[i] = this.articleDetailData[i];
                }
            }
            if(param.categoryId !== 243) {
                param.dietTypeId = '';
            }
            if (!this.isSubmit) {
              this.isSubmit = true;
              this.fullscreenLoading = true;
              articleService.addArticleServer(param,  (data)=>{
                this.$message({
                  message:'保存成功',
                  type:'success',
                  duration:1000
                });
                setTimeout(()=>{
                  this.$router.push({path: '/operationMgt/articleMgt'});
                },1000)
              },(data)=>{
                this.isSubmit = false;
                this.fullscreenLoading = false;
              })
            }

          }
        })
      },
      deleteApprovalInput(item) {
        let index = this.articleDetailData.siteSelect.indexOf(item)
        if (index !== -1) {
          this.articleDetailData.siteSelect.splice(index, 1);
        }
      },
      addApproval() {
        this.articleDetailData.siteSelect.push({
          siteIdArr: [],
          key: Date.now()
        })
      },
    },
    computed: mapState({
      bodyHeight: state => state.global.bodyHeight,
      fixedHeightSmall: state => state.global.fixedHeightSmall,
      articleItem: state => state.article.articleItem,
      siteArr: state => {
        let arr = [];
        let data = state.site.siteTree;
        if(data.children){
          for(let i=0;i<data.children.length;i++) {
            let item = data.children[i];
            if(item.children && item.children.length>0) {
              arr.push(item);
            }
          }
        }
        return arr;
      }
    }),
    mounted: function () {
      console.log("**************");
      console.log(this.$route.params);
      let articleId = this.$route.params.id;
      this.dataSource = this.$route.params.dataSource;
      this.siteName = this.$route.params.siteName;
      articleService.loadNextArticleItemServer(data=>{
        this.dietTypeArr = data.data;
      })
      if(articleId) {
        this.onlyPub = true;
        this.breadcrumbData.list[2].name = '查看文章';
        this.articleDetailData.id = articleId;
        articleService.loadArticleDetail({id:articleId},data => {
          let detail = data.data;
          let articleDetailData =  this.articleDetailData;
          articleDetailData.id = detail.id;
          articleDetailData.title = detail.title;
          articleDetailData.source = detail.source;
          articleDetailData.content = detail.content;
          articleDetailData.summary = detail.summary;
          articleDetailData.imageId = detail.coverId?detail.coverId+'':'';
          articleDetailData.categoryId = detail.categoryId;
          if(detail.categoryId === 243) {
            articleDetailData.dietTypeId = detail.dietTypeId;
          }
          this.imageUrl = detail.coverPath;
          let positions = detail.positions.split(",");
          let labelArr = [];
          for (let i = 0; i < positions.length; i++) {
            switch (positions[i]) {
              case 'COMMUNITY_HEADLINES' :
                labelArr.push('热点资讯');
                break;
              case 'COMMUNITY_ANNOUNCEMENT' :
                labelArr.push('社区公告');
                break;
//              case  'ARTICLE_FOR_ACTIVE':
//                labelArr.push('活动入口');
//                break;
              case 'HEALTH_DIET':
                labelArr.push('健康食谱');
                break;
            }
          }
          articleDetailData.positionCheckList = labelArr;
        })
      }else{
        this.breadcrumbData.list[2].name = '写文章';
        this.articleDetailData.siteSelect.push({
          key: Date.now(),
          siteIdArr: [],
        })
      }
    },
    activated(){
    },
    data() {
      let validateContent = (rule, val, callback) => {
        let value = (val + '').trim();
        if (value === '') {
          callback('请输入正文');
        } else {
          callback();
        }
      };
      let validatePublishTime = (rule, val, callback) => {
        if(val === '') {
          callback('请选择发布时间')
        }else{
          let currentTime = new Date().getTime();
          if(!(val.getTime() > currentTime)) {
            callback('发布时间必须晚于当前时间');
          }
          callback()
        }
      };
      return {
        dietTypeArr: [],
        datePicker: {
          disabledDate(val) {
            return new Date() > new Date(val.getTime()+24*60*60*1000);
          }
        },
        siteName: '',
        dataSource: '',
        options: {
          value: 'id',
          label:'name',
          children: 'children'
        },
        fullscreenLoading: false,
        supportFile: ['.jpeg', '.jpg', '.png', '.gif'],
        isSubmit: false,
        onlyPub: false,
        breadcrumbData: {
          list: [
           {
              name: '运营',
              path: null,
             clickAble: false
            },{
              name: '文章管理',
              path: '/operationMgt/articleMgt',
              clickAble: true
            },{
              name: '写文章',
              path: null,
              clickAble: false
            }
          ],
          returnData: {
            isReturn: true, path: null
          },
          iconName: 'operation-icon',
        },
        articleDetailData: {
          id: "",
          title: "",
          source: "",
          content: "",
          summary: "",
          positions: "",
          imageId: "",
          needPublish: "",
          siteIds:'',
          publishType: 'Now',
          timingPublishTime: '',
          categoryId: '',
          dietTypeId: '',

          positionCheckList: [],
          timingPublishTime_: '',
          siteSelect: [],

        },
        imageUrl: '',
        positionOptions: ['热点资讯', '社区公告','健康食谱'],
        submitFormRules: {
          categoryId: {required: true,message:'请选择分类',trigger: 'change',type:'number'},
          dietTypeId: {required: true,message:'请选择食谱分类',trigger: 'change',type:'number'},
          title: [
            {required: true, message: "请输入标题", trigger: 'change'},
            {max: 30, message: '不超过30个字符', trigger: 'change'},
            {min: 5, message: '不少于5个字符', trigger: 'change'}
          ],
          source: [
            {required: true, message: "请输入来源", trigger: 'change'},
            {max: 8, message: '不超过8个字符', trigger: 'change'}
          ],
          content: {validator: validateContent, trigger: 'change'},
//          imageId: {required: true,message:'请上传封面',trigger: 'change'},
          positionCheckList: {required:true ,message:'请选择展示位置', type:'array', trigger: 'change'},
          timingPublishTime_: {validator: validatePublishTime,  trigger: 'change'},
        },
      }
    }
  }
</script>

<style lang="less">
  @import '../../../assets/style/main.less';
  .add-article-box {
    .addNode{
      display:inline;
      cursor:pointer;
      color: @creatButton;
      i{
        color:@creatButton;
      }
      &:hover{
        .my-opacity();
      }
    }
    .add-article-content-box {
      margin-top: 0px;
      padding: 30px;
      background-color: #fff;
    }
    .top-form .el-form-item {
      width: 600px;
    }

    .avatar-uploader .el-upload {
      border: 1px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
      border-color: @primaryColor;
    }
    .avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      line-height: 178px;
      text-align: center;
    }
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .ensure-save-box {
      background-color: @primaryColor;
      padding: 30px 40px;
      .color1 {
        color: @primaryColor;
      }
      .color2 {
        color: @creatButton;
      }
      .btnStyle {
        min-width: 120px;
        display: inline-block;
        height: 40px;
        background-color: #fff;
        text-align: center;
        line-height: 40px;
        border-radius: 5px;
        margin-right: 60px;
        cursor: pointer;
        font-size: 14px;
      }
    }
  }

  .ql-container .ql-editor {
    min-height: 320px;
    padding-bottom: 16px;
    max-height: 400px;
  }

  .ckeditor-content-size {
    width: 800px !important;
  }
</style>
